//
//  SVListViewController.m
//  ShortVideo-ccinon
//
//  Created by LIN TONG on 2017/6/19.
//  Copyright © 2017年 LIN TONG. All rights reserved.
//

#import "SVListViewController.h"
#import "SVConfig.h"
#import "SVNavigationBar.h"
#import "SVQRCode.h"
#import "QRCodeUtil.h"
#import "SVVideo.h"
#import "SVQrcodeDetailController.h"
#import "UIActionSheet+Blocks.h"
#import "UIButton+Indexpath.h"
#import "SVQRcodeEditViewController.h"
#import "SVAPIReqeust.h"

@interface SVListViewController()<UITableViewDataSource,UITableViewDelegate>{
    NSMutableArray *qrcodeLists;
    UITableView    *contentTable;
    
    UIView         *footView;
}

@end

@implementation SVListViewController
- (void)viewDidLoad{
    [super viewDidLoad];
    
    qrcodeLists = [NSMutableArray arrayWithCapacity:0];
    
    SVNavigationBar *naviBar = [[SVNavigationBar alloc]init];
    [naviBar setQrcodeHandler:^{
        [QRCodeUtil pushQRCodeVC:self WithCompletionHandler:^(BOOL success, NSString *result) {
            if(success && result && result.length){
                NSArray *params = [result componentsSeparatedByString:@"?"];
                
                NSInteger vod_qr_id = -1;
                for(NSString * par in params){
                    if([par rangeOfString:@"vod_qr_id"].location != NSNotFound){
                        vod_qr_id = [[[par componentsSeparatedByString:@"="] lastObject]integerValue];
                    }
                }
                
                if(vod_qr_id != -1){
                    [SVAPIReqeust svRequestAPI:API(@"/mct/vod/qrcode/dts") method:@"GET" parametors:@{@"vod_qr_id":@(vod_qr_id)} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
                        if(success){
                            if([data objectForKey:@"data"]!=[NSNull null] && [data objectForKey:@"data"]){
                                NSDictionary *dic = [data objectForKey:@"data"];
                                SVQRCode *qrcode = [[SVQRCode alloc]init];
                                qrcode.name = [dic objectForKey:@"vod_qr_title"];
                                qrcode.des = [dic objectForKey:@"vod_qr_describe"];
                                qrcode.companyBrand = [dic objectForKey:@"vod_qr_brand"];
                                qrcode.ID = [[dic objectForKey:@"vod_qr_id"]integerValue];
                                qrcode.companyID = [[dic objectForKey:@"cpn_id"]integerValue];
                                qrcode.createTime = [dic objectForKey:@"vod_qr_add_time"];
                                qrcode.capacity = [[dic objectForKey:@"vod_qr_size_tot"]doubleValue];
                                qrcode.usage = [[dic objectForKey:@"vod_qr_size_use"]doubleValue];
                                qrcode.endTime = [dic objectForKey:@"vod_qr_end_time"];
                                
                                SVQrcodeDetailController *detailVC = [[SVQrcodeDetailController alloc]init];
                                detailVC.qrcode = qrcode;
                                [self.navigationController pushViewController:detailVC animated:YES];
                                
                            }else{
                                SVQRcodeEditViewController *editVC = [[SVQRcodeEditViewController alloc]init];
                                editVC.state = SV_QRCODE_NEW;
                                
                                SVQRCode *qrcode = [[SVQRCode alloc]init];
                                qrcode.ID = vod_qr_id;
                                
                                editVC.qrcode = qrcode;
                                [self.navigationController pushViewController:editVC animated:YES];
                            }
                        }
                    }];
                }
            }
        }];
    }];
    [naviBar setTitle:@"二维码管理"];
    [self.view addSubview:naviBar];
    
    contentTable = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(naviBar.frame), __SCREEN_WIDTH__, S(384))];
    contentTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    contentTable.dataSource = self;
    contentTable.delegate = self;
    [self.view addSubview:contentTable];
    
    footView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(contentTable.frame), __SCREEN_WIDTH__, __SCREEN_HEIGHT__-CGRectGetMaxY(contentTable.frame))];
    footView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:footView];
    [self createFootView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadQrcodeLists];
}

- (void)createFootView{
    UIButton *plusButton = [[UIButton alloc]initWithFrame:CGRectMake(S(118), S(10), S(57), S(72))];
    plusButton.center = CGPointMake(__SCREEN_WIDTH__/2.0, plusButton.center.y);
    plusButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 15, 0);
    plusButton.titleLabel.font = Font(11);
    [plusButton setTitleColor:UIColorMake(66, 66, 66, 1) forState:UIControlStateNormal];
    [plusButton setImage:[UIImage imageNamed:@"qr_plus"] forState:UIControlStateNormal];
    [footView addSubview:plusButton];
    
    UILabel *des = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(plusButton.frame)-S(15), __SCREEN_WIDTH__, S(15))];
    des.textAlignment = NSTextAlignmentCenter;
    des.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:12];
    des.textColor = UIColorMake(100, 100, 100, 1);
    des.text = @"点击添加二维码";
    [footView addSubview:des];
    
    [plusButton addTarget:self action:@selector(clickPlustButton:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *copyright = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(footView.frame)-S(7)-S(15), __SCREEN_WIDTH__, S(15))];
    copyright.textAlignment = NSTextAlignmentCenter;
    copyright.font = Font(12);
    copyright.textColor = UIColorMake(249, 74, 0, 1);
    copyright.text = @"copyright@ccinon";
    [footView addSubview:copyright];
}

- (void)clickMoreButton:(UIButton *)sender{
    [UIActionSheet showInView:self.view withTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"编辑",@"删除二维码"] tapBlock:^(UIActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
        
        NSIndexPath *clickPath = sender.indexPath;
        if(buttonIndex == 0){
            SVQRcodeEditViewController *editVc = [[SVQRcodeEditViewController alloc]init];
            editVc.state = SV_QRCODE_EDIT;
            editVc.qrcode = qrcodeLists[clickPath.row];
            [self.navigationController pushViewController:editVc animated:YES];
        }else if(buttonIndex == 1){
            SVQRCode *deleteCode = qrcodeLists[clickPath.row];
            [SVAPIReqeust svRequestAPI:API(@"/mct/vod/qrcode/del") method:@"GET" parametors:@{@"vod_qr_id":[NSString stringWithFormat:@"%ld",deleteCode.ID]} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
                if(success){
                    [qrcodeLists removeObjectAtIndex:clickPath.row];
                    [contentTable reloadData];
                }
            }];
        }
    }];
}

- (void)clickPlustButton:(UIButton *)sender{
    [QRCodeUtil pushQRCodeVC:self WithCompletionHandler:^(BOOL success, NSString *result) {
        if(success && result && result.length){
            NSArray *params = [result componentsSeparatedByString:@"?"];
            
            NSInteger vod_qr_id = -1;
            for(NSString * par in params){
                if([par rangeOfString:@"vod_qr_id"].location != NSNotFound){
                    vod_qr_id = [[[par componentsSeparatedByString:@"="] lastObject]integerValue];
                }
            }
            
            if(vod_qr_id != -1){
                
                [SVAPIReqeust svRequestAPI:API(@"/mct/vod/qrcode/dts") method:@"GET" parametors:@{@"vod_qr_id":@(vod_qr_id)} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
                    if(success){
                        if([data objectForKey:@"data"]!=[NSNull null] && [data objectForKey:@"data"]){
                            NSDictionary *dic = [data objectForKey:@"data"];
                            SVQRCode *qrcode = [[SVQRCode alloc]init];
                            qrcode.name = [dic objectForKey:@"vod_qr_title"];
                            qrcode.des = [dic objectForKey:@"vod_qr_describe"];
                            qrcode.companyBrand = [dic objectForKey:@"vod_qr_brand"];
                            qrcode.ID = [[dic objectForKey:@"vod_qr_id"]integerValue];
                            qrcode.companyID = [[dic objectForKey:@"cpn_id"]integerValue];
                            qrcode.createTime = [dic objectForKey:@"vod_qr_add_time"];
                            qrcode.capacity = [[dic objectForKey:@"vod_qr_size_tot"]doubleValue];
                            qrcode.usage = [[dic objectForKey:@"vod_qr_size_use"]doubleValue];
                            qrcode.endTime = [dic objectForKey:@"vod_qr_end_time"];
                            
                            SVQrcodeDetailController *detailVC = [[SVQrcodeDetailController alloc]init];
                            detailVC.qrcode = qrcode;
                            [self.navigationController pushViewController:detailVC animated:YES];
                            
                        }else{
                            SVQRcodeEditViewController *editVC = [[SVQRcodeEditViewController alloc]init];
                            editVC.state = SV_QRCODE_NEW;
                            
                            SVQRCode *qrcode = [[SVQRCode alloc]init];
                            qrcode.ID = vod_qr_id;
                            
                            editVC.qrcode = qrcode;
                            [self.navigationController pushViewController:editVC animated:YES];
                        }
                    }
                }];
            }
        }
    }];
}

- (void)loadQrcodeLists{
    [SVAPIReqeust svRequestAPI:API(@"/mct/vod/qrcode/lst") method:@"GET" parametors:@{@"cur":@"1",@"size":@"20"} completionBlock:^(NSString *requestURL, BOOL success, NSDictionary *data, NSError *error) {
        if(success){
            NSLog(@"%@",data);
            [qrcodeLists removeAllObjects];
            
            NSArray *codes = [data objectForKey:@"data"];
            for(int i=0;i<codes.count;i++){
                NSDictionary *dic = codes[i];
                SVQRCode *qrcode = [[SVQRCode alloc]init];
                qrcode.name = [dic objectForKey:@"vod_qr_title"];
                qrcode.des = [dic objectForKey:@"vod_qr_describe"];
                qrcode.companyBrand = [dic objectForKey:@"vod_qr_brand"];
                qrcode.ID = [[dic objectForKey:@"vod_qr_id"]integerValue];
                qrcode.companyID = [[dic objectForKey:@"cpn_id"]integerValue];
                qrcode.createTime = [dic objectForKey:@"vod_qr_add_time"];
                qrcode.capacity = [[dic objectForKey:@"vod_qr_size_tot"]doubleValue];
                qrcode.usage = [[dic objectForKey:@"vod_qr_size_use"]doubleValue];
                qrcode.endTime = [dic objectForKey:@"vod_qr_end_time"];
                [qrcodeLists addObject:qrcode];
            }
            [contentTable reloadData];
        }
    }];
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
#pragma mark - table view delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  qrcodeLists.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return S(64);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifier = @"identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell){
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIImageView *iconImage = [[UIImageView alloc]initWithFrame:CGRectMake(S(9), S(9), S(46), S(46))];
        iconImage.tag = 1001;
        iconImage.image = [UIImage imageNamed:@"qr_icon"];
        [cell addSubview:iconImage];
        
        UILabel *videoName = [[UILabel alloc]initWithFrame:CGRectMake(S(71), S(8), S(200), S(20))];
        videoName.textColor = UIColorMake(30, 30, 30, 1);
        [videoName setFont:[UIFont fontWithName:@"STHeitiSC-Medium" size:16]];
        videoName.tag = 1002;
        [cell addSubview:videoName];
        
        UILabel *remainTime = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(videoName.frame), CGRectGetMaxY(videoName.frame)+S(4), CGRectGetWidth(videoName.frame), S(20))];
        remainTime.textColor = UIColorMake(100, 100, 100, 1);
        [remainTime setFont:[UIFont fontWithName:@"STHeitiSC-Medium" size:12]];
        remainTime.tag = 1003;
        [cell addSubview:remainTime];
        
        UILabel *remainCapacity = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(videoName.frame)-S(150), CGRectGetMinY(remainTime.frame), S(150), S(20))];
        remainCapacity.textColor = UIColorMake(100, 100, 100, 1);
        remainCapacity.textAlignment = NSTextAlignmentRight;
        [remainCapacity setFont:[UIFont fontWithName:@"STHeitiSC-Medium" size:12]];
        remainCapacity.tag = 1006;
        [cell addSubview:remainCapacity];
        
        UIButton *moreButton = [[UIButton alloc]initWithFrame:CGRectMake(__SCREEN_WIDTH__-S(40), 0, S(40), S(25))];
        moreButton.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
        moreButton.center = CGPointMake(moreButton.center.x, S(32));
        moreButton.tag = 1005;
        [moreButton setImage:[UIImage imageNamed:@"more_info"] forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(clickMoreButton:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:moreButton];
        
        UIView *horline = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMinX(videoName.frame), S(64)-S(1), __SCREEN_WIDTH__-S(10)-CGRectGetMinX(videoName.frame), S(1))];
        horline.backgroundColor = UIColorMake(122, 122, 122, 1);
        [cell addSubview:horline];
    }
    
    UILabel *name = [cell viewWithTag:1002];
    UILabel *capacity = [cell viewWithTag:1006];
    UILabel *remainTime = [cell viewWithTag:1003];
    UIButton *moreButton = [cell viewWithTag:1005];
    
    moreButton.indexPath = indexPath;
    
    SVQRCode *qrcode = qrcodeLists[indexPath.row];
    name.text = qrcode.name;
    capacity.text = @"剩余容量:5G";
    remainTime.text = [NSString stringWithFormat:@"剩余时间:%@",@"3个月零15天"];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SVQRCode *qr = qrcodeLists[indexPath.row];
    SVQrcodeDetailController *detail = [[SVQrcodeDetailController alloc]init];
    detail.qrcode = qr;
    [self.navigationController pushViewController:detail animated:YES];
}

@end
